/*******************************************************************************
 * Package: com.song.es
 * Type:    ESTestWeb
 * Date:    2024-01-08 21:48
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.es.web;

import com.song.common.util.JsonUtils;
import com.song.es.dto.DogDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述：
 *
 * @author Songxianyang
 * @date 2024-01-08 21:48
 */
@Slf4j
@Api(tags = "es-简单操作")
@RestController
@RequestMapping("/es")
public class ESTestWeb {
    @Resource
    public RestHighLevelClient restHighLevelClient;

    @GetMapping("create")
    @ApiOperation("创建索引")
    public void create(String index) throws IOException {
        //sys_user
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        log.info("是否成功{}", createIndexResponse.isAcknowledged());
        log.info("返回的对象{}", createIndexResponse);
    }

    @GetMapping("get")
    @ApiOperation("查询索引是否存在")
    public Boolean get(String index) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest(index);
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        return exists;
    }

    @GetMapping("delete")
    @ApiOperation("删除索引")
    public Boolean delete(String index) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        log.info("是否成功{}", delete.isAcknowledged());
        log.info("返回的对象{}", delete);
        return Boolean.TRUE;
    }

    @PostMapping("add-document")
    @ApiOperation("插入文档")
    public IndexResponse addDocument(@RequestBody DogDto dto) throws IOException {
        // 创建请求
        IndexRequest request = new IndexRequest("sys_song");
        // 制定规则 PUT /sys_song/_doc/1
        request.id(dto.getId());

        request.timeout(TimeValue.timeValueMillis(1000));// request.timeout("1s")
        // 将我们的数据放入请求中

        request.source(JsonUtils.toJson(dto), XContentType.JSON);
        // 客户端发送请求，获取响应的结果
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        return response;
    }

    @GetMapping("get-doc")
    @ApiOperation("获取文档")
    public GetResponse getDoc(String index, String id) throws IOException {
        GetRequest request = new GetRequest(index, id);
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        return response;
    }


    @PostMapping("update-doc")
    @ApiOperation("更新文档文档")
    public Boolean updateDoc(@RequestBody DogDto dto) throws IOException {
        UpdateRequest request = new UpdateRequest("sys_song", dto.getId());

        request.doc(JsonUtils.toJson(dto), XContentType.JSON);
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);

        System.out.println(response.status()); // OK
        restHighLevelClient.close();
        return Boolean.TRUE;
    }


    @GetMapping("del-doc")
    @ApiOperation("删除文档")
    public String delDoc(String index, String id) throws IOException {
        DeleteRequest request = new DeleteRequest(index, id);
        request.timeout("1s");
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        return response.status().toString();
    }
    @GetMapping("list-doc")
    @ApiOperation("list文档")
    public SearchHits listDoc(String index, String id) throws IOException {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.should(QueryBuilders.matchPhraseQuery("desc","严"));
        boolQuery.should(QueryBuilders.matchPhraseQuery("name","张"));

        String s = boolQuery.toString();

        // 1.创建查询请求对象
        SearchRequest searchRequest = new SearchRequest();
        // 2.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// (1)查询条件 使用QueryBuilders工具类创建
        // 精确查询
        //TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "liuyou");
        //        // 匹配查询
        //        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        // (2)其他<可有可无>：（可以参考 SearchSourceBuilder 的字段部分）
        // 设置高亮
        searchSourceBuilder.highlighter(new HighlightBuilder());
                // 分页
                //searchSourceBuilder.from();
                //searchSourceBuilder.size();
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // (3)条件投入
        searchSourceBuilder.query(boolQuery);
        // 3.添加条件到请求
        searchRequest.source(searchSourceBuilder);
        // 4.客户端查询请求
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 5.查看返回结果
        SearchHits hits = search.getHits();
        return hits;
    }


}
